<?php
namespace app\super\controller;
use think\Db;
use app\super\validate\BookValidate;
//书籍管理
class BookController extends CommonController {
    /**
     * 获取书籍信息
     */
    public function getBookInfo(){
        $where = '';
        $rows = $_POST['rows'];
        $page = $_POST['page'];
        if($_POST['keyword']!=''){
            $keyword = $_POST['keyword'];
            $where['a.book_name|ut.team_name|ut.team_number'] = array('like',"%$keyword%");
        }

        if($_POST['book_status']!=''){//状态
            $where['a.book_status'] = $_POST['book_status'];
        }
        if($_POST['start']!=''){//时间
            $where['a.book_publish_time'] =array('>=',$_POST['start']);
        }elseif ($_POST['end']!=''){
            $where['a.book_publish_time'] =array('<=',$_POST['end']);
        }elseif ($_POST['start']!=''&&$_POST['end']!=''){
            $where['a.book_publish_time'] =array('between',array($_POST['start'],$_POST['end']));

        }
//        if($_POST['end']!=''){//时间
//            $where['a.book_publish_time'] =array('<=',$_POST['end']);
//        }

        $res = Db::table('up_book')->alias('a')
            ->join('up_u_user u','u.user_id = a.book_send_publisher_id','left')
            ->join('up_team ut','ut.team_id = a.book_publisher','left')
            ->join('up_u_admin uua','uua.user_id = a.book_send_publisher_id','left')
            ->where($where)
            ->limit($rows * ($page - 1), $rows)
            ->field('u.user_username,a.*,ut.team_name,ut.team_number,uua.user_username as username')
            ->order('a.book_publish_time DESC')
            ->select();
        $total = Db::table('up_book')->alias('a')
            ->join('up_u_user u','u.user_id = a.book_send_publisher_id','left')
            ->join('up_team ut','ut.team_id = a.book_publisher','left')
            ->join('up_u_admin uua','uua.user_id = a.book_send_publisher_id','left')
            ->where($where)
            ->count();
        $data['total'] = $total;
        $data['rows'] = $res;
        return json_encode($data);
    }

    /**
     * 发布
     */
    public function Confirmation(){
        $cid = $_POST['cid'];
        if($cid!=''){
            $where['book_id'] = $cid;
            $data['book_status'] = 1;//审核通过
            $res =  Db::table('up_book')->where($where)->update($data);
            if($res){
                $returnData['status'] = 1;
                $returnData['msg'] = "发布成功";
                return json_encode($returnData);
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = "发布失败";
                return json_encode($returnData);
            }
        }else{
            $returnData['status'] = 0;
            $returnData['msg'] = "传递参数错误";
            return json_encode($returnData);
        }
    }

    /***
     * 取消发布
     */
    public function QxConfirmation(){
        $cid = $_POST['cid'];
        if($cid!=''){
            $where['book_id'] = $cid;
            $data['book_status'] = 2;//审核通过
            $res =  Db::table('up_book')->where($where)->update($data);
            if($res){
                $returnData['status'] = 1;
                $returnData['msg'] = "取消发布成功";
                return json_encode($returnData);
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = "取消发布失败";
                return json_encode($returnData);
            }
        }else{
            $returnData['status'] = 0;
            $returnData['msg'] = "传递参数错误";
            return json_encode($returnData);
        }
    }

    /**
     * 删除此课程
     */
    public function delConfirmation(){
        $cid = $_POST['cid'];
        if($cid!=''){
            $where['book_id'] = $cid;
            $res =  Db::table('up_book')->where($where)->delete();
            $whereMap['chapter_book_id'] = $cid;
            Db::table('up_book_chapter')->where($whereMap)->delete();

            if($res){
                $returnData['status'] = 1;
                $returnData['msg'] = "删除成功";
                return json_encode($returnData);
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = "删除失败";
                return json_encode($returnData);
            }
        }else{
            $returnData['status'] = 0;
            $returnData['msg'] = "传递参数错误";
            return json_encode($returnData);
        }
    }

    /***
     * 添加页面
     */
    public function addBook(){
        $res = array();
        $team_id = Db::table('up_team')->where('is_team',1)->column('team_id');
        $team= Db::table('up_team')->where('is_team',1)->field('team_id,team_name')->select();
        $this->assign('team',$team);
        if(count($team_id)>0){
            $where['team_id'] = array('IN',$team_id);
            $res = Db::table('up_team_members')->alias('a')
                ->join('up_u_user uuu','uuu.user_id = a.team_member_user_id')
                ->field('uuu.user_id,uuu.user_phone,uuu.user_username')
                ->where($where)
                ->select();
        }
        $this->assign('res',$res);
    return $this->fetch('book/addBook');
    }

    /**
     * 添加功能
     */
    public function insertBook(){
        $validata = new BookValidate();
        if(!$validata->check($_POST)) {
            $returnData['status'] = 0;
            $returnData['msg'] = $validata->getError();
            return json_encode($returnData);
        }
        $uid = session('loginSession')['user_id'];
        if($_FILES['fileImg']['name']==''){
            $returnData['status'] = 0;
            $returnData['msg'] = "上传文件格式不正确或者上传文件不能为空";
            return json_encode($returnData);
        }
        $rand = date('YmdHis').rand(100000,999999);
        $exe = explode('.',$_FILES['fileImg']['name']);
        $filePath = $_FILES['fileImg']['tmp_name'];
        $info = $this->qnCommon(2,$rand,$exe[1],$filePath);
        if($info['status']!=200) {
            $returnData['status'] = 0;
            $returnData['msg'] = "上传文件格式不正确";
            return json_encode($returnData);
        }else{
            $data['book_img'] = QiNiu.$info['key'];;
        }
        $data['book_id'] = $this->getRandChar(32);
        $data['book_introduction'] = $_POST['book_introduction'];
        $data['book_name'] =  $_POST['book_name'];
        $data['book_status'] = 1;
        $data['book_publish_time'] =date('Y-m-d H:i:s');
        $data['book_send_publisher_id'] = $uid;
        $res = Db::table('up_book')->insert($data);
        if($res){
            return json_encode(array("status" => 1, "msg" => "发布成功！"));
        }else{
            return json_encode(array("status" => 0, "msg" => "发布失败！"));
        }
    }

    /**
     * 编辑书籍页面
     */
    public function updateBook(){
//        $uid = session('loginSession')['user_id'];

        $cid = $_POST['nid'];
        $res = Db::table('up_book')->where('book_id',$cid)->find();
        $this->assign('res',$res);
//        $project_id= Db::table('up_book')->where('book_id',$cid)->field('book_id,book_send_publisher_id')->find();
//        if($project_id['book_send_publisher_id']==$uid){
//            return $this->fetch('book/updateBook');
//        }else{
//            return 1;
//        }
        return $this->fetch('book/updateBook');
    }

    /**
     * 编辑功能
     */
    public function updateBookInfo(){
        $validata = new BookValidate();
        if(!$validata->check($_POST)) {
            $returnData['status'] = 0;
            $returnData['msg'] = $validata->getError();
            return json_encode($returnData);
        }
        if(!empty($_FILES['fileImg']['type'])){
            $rand = date('YmdHis').rand(100000,999999);
            $exe = explode('.',$_FILES['fileImg']['name']);
            $filePath = $_FILES['fileImg']['tmp_name'];
            $info = $this->qnCommon(2,$rand,$exe[1],$filePath);
            if($info['status']!=200) {
                $returnData['status'] = 0;
                $returnData['msg'] = "上传文件格式不正确";
                return json_encode($returnData);
            }else{
                $data['book_img'] = QiNiu.$info['key'];;
            }
        }

        $data['book_introduction'] = $_POST['book_introduction'];
        $data['book_name'] =  $_POST['book_name'];
        $res = Db::table('up_book')->where('book_id',$_POST['book_id'])->update($data);
        if($res){
            $returnData['status'] = 1;
            $returnData['msg'] = "修改成功";
            return json_encode($returnData);
        }else{
            $returnData['status'] = 0;
            $returnData['msg'] = "修改失败";
            return json_encode($returnData);
        }
    }

    /**
     * 书籍目录列表
     */
    public function catalog(){
        $where['chapter_book_id'] = $_POST['book_id'];
        $rows = $_POST['rows'];
        $page = $_POST['page'];
        if($_POST['keyword']!=''){
            $keyword = $_POST['keyword'];
            $where['a.chapter_name|ub.book_name|ut.team_name|ut.team_number'] = array('like',"%$keyword%");
        }
        if($_POST['start']!=''){//时间
            $where['a.chapter_time'] =array('>=',$_POST['start']);
        }elseif ($_POST['end']!=''){
            $where['a.chapter_time'] =array('<=',$_POST['end']);
        }elseif ($_POST['start']!=''&&$_POST['end']!=''){
            $where['a.chapter_time'] =array('between',array($_POST['start'],$_POST['end']));

        }
//        if($_POST['end']!=''){//时间
//            $where['a.chapter_time'] =array('<=',$_POST['end']);
//        }

//        $whereMap['book_status'] = 1;//发布
//        $book_id = Db::table('up_book')->where($whereMap)->column('book_id');
//        $where['chapter_book_id'] = array('IN',$book_id);
        $res = Db::table('up_book_chapter')->alias('a')
            ->join('up_u_user u','u.user_id = a.chapter_user_id','left')
            ->join('up_book ub','ub.book_id = a.chapter_book_id','left')
            ->join('up_team ut','ut.team_id = ub.book_publisher','left')
            ->join('up_u_admin uua','uua.user_id = a.chapter_user_id','left')
            ->where($where)
            ->limit($rows * ($page - 1), $rows)
            ->field('u.user_username,a.*,ub.book_name,ut.team_name,ut.team_number,uua.user_username as username')
            ->order('a.chapter_time DESC')
            ->select();
        $total = Db::table('up_book_chapter')->alias('a')
            ->join('up_u_user u','u.user_id = a.chapter_user_id')
            ->join('up_book ub','ub.book_id = a.chapter_book_id')
            ->join('up_team ut','ut.team_id =ub.book_publisher','left')
            ->join('up_u_admin uua','uua.user_id = a.chapter_user_id','left')
            ->where($where)
            ->count();

        $data['total'] = $total;
        $data['rows'] = $res;
        return json_encode($data);
    }

    /**
     * 删除书籍目录
     */
    public function delBookCatalog(){
        $cid = $_POST['cid'];
//        $result = Db::table('up_book_chapter')->where('chapter_id',$cid)->find();
//        $uid = session('loginSession')['user_id'];
//        if($uid!=$result['chapter_user_id']){
//            $returnData['status'] = 0;
//            $returnData['msg'] = "不能删除不属于自己的书籍目录";
//            return json_encode($returnData);
//        }

        if($cid!=''){
            $where['chapter_id'] = $cid;
            $res = Db::table('up_book_chapter')->where($where)->delete();

            if($res){
                $returnData['status'] = 1;
                $returnData['msg'] = "删除成功";
                return json_encode($returnData);
            }else{
                $returnData['status'] = 0;
                $returnData['msg'] = "删除失败";
                return json_encode($returnData);
            }
        }else{
            $returnData['status'] = 0;
            $returnData['msg'] = "传递参数错误";
            return json_encode($returnData);
        }
    }

    /**
     * 添加书籍目录信息
     */
    public function addBookCatalog(){
        $res = array();
         $book = $_POST['book_id'];
//        $uid = session('loginSession')['user_id'];
//        $whereMapS['book_status'] = 1;//发布
//        $whereMapS['book_send_publisher_id'] = $uid;
//        $book = Db::table('up_book')->where($whereMapS)->select();
        $book_name = Db::table('up_book')->where('book_id',$book)->value('book_name');
        $team_id = Db::table('up_team')->where('is_team',1)->column('team_id');

        if(count($team_id)>0){
            $where['team_id'] = array('IN',$team_id);
            $res = Db::table('up_team_members')->alias('a')
                ->join('up_u_user uuu','uuu.user_id = a.team_member_user_id')
                ->field('uuu.user_id,uuu.user_phone,uuu.user_username')
                ->where($where)
                ->select();
        }
        $this->assign('res',$res);
        $this->assign('book_name',$book_name);
        $this->assign('book',$book);
        return $this->fetch('book/addBookCatalog');

    }

    /*
     * 添加功能
     */
    public function insertBookCatalog(){
        set_time_limit(0);

        if($_POST['chapter_book_id']==''){
            $returnData['status'] = 0;
            $returnData['msg'] = "课程分类不能为空";
            return json_encode($returnData);
        }
        if($_POST['chapter_name']==''){
            $returnData['status'] = 0;
            $returnData['msg'] = "目录名称不能为空";
            return json_encode($returnData);
        }
        $uid = session('loginSession')['user_id'];
        if($_FILES['file']['name']==''){
            $returnData['status'] = 0;
            $returnData['msg'] = "上传文件不能为空";
            return json_encode($returnData);
        }
        $rands = date('YmdHis').rand(100000,999999);
        $exes = explode('.',$_FILES['file']['name']);
        $filePaths = $_FILES['file']['tmp_name'];
        $str = file_get_contents($_FILES['file']['tmp_name']);
        $list = array('UTF-8','GBK');
        $ty = '';
        foreach ($list as $item) {
            $tmp = mb_convert_encoding($str, $item, $item);
            if (md5($tmp) == md5($str)) {
                $ty = $item;
            }
        }
        if($ty!='UTF-8'){
            $data['chapter_isutf8'] = 0;
        }else{
            $data['chapter_isutf8'] = 1;
        }
        $info = $this->qnCommon(6,$rands,$exes[1],$filePaths);
        if($info['status']!=200) {
            $returnData['status'] = 0;
            $returnData['msg'] = "上传文件格式不正确";
            return json_encode($returnData);
        }else{
            $data['chapter_file_img'] = QiNiu.$info['key'];;

        }
        $data['chapter_id'] = $this->getRandChar(32);
        $data['chapter_name'] = $_POST['chapter_name'];
        $data['chapter_book_id'] = $_POST['chapter_book_id'];
        $data['chapter_time'] =date('Y-m-d H:i:s');
        $data['chapter_user_id'] = $uid;

        $res = Db::table('up_book_chapter')->insert($data);
        if($res){
            return json_encode(array("status" => 1, "msg" => "发布成功！"));
        }else{
            return json_encode(array("status" => 0, "msg" => "发布失败！"));
        }
    }
    public function characet($data){
        if( !empty($data) ){
            $fileType = mb_detect_encoding($data , array('UTF-8','GBK','LATIN1','BIG5','ASCII')) ;
            if( $fileType != 'UTF-8'){
                $data = mb_convert_encoding($data ,'utf-8' , $fileType);
            }
        }
        return $data;
    }

    /*
     * 编辑页面
     */
    public function updateBookCatalog(){
        $uid = session('loginSession')['user_id'];

        $nid = $_POST['nid'];
        $res = Db::table('up_book_chapter')->where('chapter_id',$nid)->find();
//        if($res['chapter_user_id']!=$uid){
//            return 1;
//        }
//        $whereMap['book_publisher'] = 1;//TODO 缺少团队ID
        $whereMap['book_status'] = 1;//发布
        $whereMap['book_send_publisher_id'] = $uid;
        $book = Db::table('up_book')->where($whereMap)->select();
        $this->assign('book',$book);
        $this->assign('res',$res);
        return $this->fetch('book/updateBookCatalog');
    }

    /**
     * 书籍目录编辑功能
     */
    public function updateBookCatalogInfo(){
//        $uid = session('loginSession')['user_id'];
//        $result = Db::table('up_book')->where('book_id',$_POST['chapter_book_id'])->field('book_send_publisher_id')->find();
//        if($result['book_send_publisher_id']!=$uid){
//            $returnData['status'] = 0;
//            $returnData['msg'] = "不能编辑不属于自己发布的书籍中的课程目录";
//            return json_encode($returnData);
//        }
        set_time_limit(0);
        if(!empty($_FILES['file']['name'])){
            $rands = date('YmdHis').rand(100000,999999);
            $exes = explode('.',$_FILES['file']['name']);
            $filePaths = $_FILES['file']['tmp_name'];

            $str = file_get_contents($_FILES['file']['tmp_name']);
            $list = array('UTF-8','GBK');
            $ty = '';
            foreach ($list as $item) {
                $tmp = mb_convert_encoding($str, $item, $item);
                if (md5($tmp) == md5($str)) {
                    $ty = $item;
                }
            }
            if($ty!='UTF-8'){
                $data['chapter_isutf8'] = 0;
            }else{
                $data['chapter_isutf8'] = 1;
            }
            $info = $this->qnCommon(6,$rands,$exes[1],$filePaths);
            if($info['status']!=200) {
                $returnData['status'] = 0;
                $returnData['msg'] = "上传文件格式不正确";
                return json_encode($returnData);
            }else{
                $data['chapter_file_img'] = QiNiu.$info['key'];;

            }
        }
        $where['chapter_id'] = $_POST['chapter_id'];
        $data['chapter_name'] = $_POST['chapter_name'];
//        $data['chapter_book_id'] = $_POST['chapter_book_id'];
        $res = Db::table('up_book_chapter')->where($where)->update($data);
        if($res){
            return json_encode(array("status" => 1, "msg" => "修改成功！"));
        }else{
            return json_encode(array("status" => 0, "msg" => "修改失败！"));
        }
    }
}